import {UserActions} from './user';

const initialState = {
  serviceData: {},
  chargeRecord: {},
};

export const ServiceActions = {
  SERVICE_UPDATE: 'services_update',
  SERVICE_RESET: 'services_reset',
  CHARGE_RECORD_REFRESH: 'charge_record_refresh',
  CHARGE_RECORD_APPEND: 'charge_record_append',
};

export function refreshChargeRecord(payload) {
  return {
    type: ServiceActions.CHARGE_RECORD_REFRESH,
    payload,
  };
}

export function appendChargeRecord(payload) {
  return {
    type: ServiceActions.CHARGE_RECORD_APPEND,
    payload,
  };
}

export function updateService(payload) {
  return {
    type: ServiceActions.SERVICE_UPDATE,
    payload,
  };
}

export function resetService() {
  return {
    type: ServiceActions.SERVICE_RESET,
  };
}

export default function serviceState(state = initialState, action) {
  const serviceData = {};
  switch (action.type) {
    case ServiceActions.SERVICE_UPDATE:
      action.payload.forEach(service => {
        serviceData[service.id] = service;
      });
      return {...state, serviceData: {...state.serviceData, ...serviceData}};
    case ServiceActions.SERVICE_RESET:
      return {};
    case ServiceActions.CHARGE_RECORD_REFRESH:
      action.payload.forEach(service => {
        serviceData[service.id] = service;
      });
      return {...state, chargeRecord: {...serviceData}};
    case ServiceActions.CHARGE_RECORD_APPEND:
      action.payload.forEach(service => {
        serviceData[service.id] = service;
      });
      return {...state, chargeRecord: {...state.chargeRecord, ...serviceData}};
    case UserActions.USER_SIGN_OUT:
      return {};
    default:
      return state;
  }
}
